package com.qf.blog.service.impl;

import com.qf.blog.vo.LikeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@Service
public class LikeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // blog:like:post:10 [101,102,103]
    // blog:like:comment:10 []
    private String likeKey = "blog:like:%s:%s";

    private String userKey = "blog:like:user:%s";

    // 10,1 -->帖子
    // 10,2 ---》评论

    /**
     * @param postId 实体的ID(帖子id，评论ID)
     * @param type   实体的类型(1(帖子)，2(评论))
     * @param userId
     * @return
     */
    public boolean isLike(Integer postId, Integer type, Integer userId) {
        // 2.准备点赞key(保存在redis的Set结构)
        String key = getLikeKey(postId, type);
        return stringRedisTemplate.opsForSet().isMember(key, userId.toString());
    }

    public void removeLike(Integer postId, Integer type, Integer userId) {
        String key = getLikeKey(postId, type);
        stringRedisTemplate.opsForSet().remove(key, userId.toString());
    }

    public void addLike(Integer postId, Integer type, Integer userId) {
        String key = getLikeKey(postId, type);
        stringRedisTemplate.opsForSet().add(key, userId.toString());
    }

    public Long likeSize(Integer postId, Integer type) {
        String key = getLikeKey(postId, type);
        return stringRedisTemplate.opsForSet().size(key);
    }

    public String getLikeKey(Integer postId, Integer type) {
        String typeName = null;
        if (type == 1) {
            typeName = "post";
        } else if (type == 2) {
            typeName = "comment";
        }
        return String.format(likeKey, typeName, postId);
    }

    public void likeUserDecr(Integer userId) {
        String key = String.format(userKey, userId);
        stringRedisTemplate.opsForValue().decrement(key);
    }

    public void likeUserIncr(Integer userId) {
        String key = String.format(userKey, userId);
        stringRedisTemplate.opsForValue().increment(key);
    }

    public Long getUserLikeNumber(Integer userId) {
        String key = String.format(userKey, userId);
        String count = stringRedisTemplate.opsForValue().get(key);
        if (!ObjectUtils.isEmpty(count)) {
            return Long.parseLong(count);
        }
        return 0L; // 把字符串转成Long类型
    }

}
